package ru.javadevelop.vegetarian.model;

import android.content.Context;
import ru.javadevelop.vegetarian.common.DB;
import ru.javadevelop.vegetarian.common.FileUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;

public class Image {
    public int id;
    public String name;
    public Date date;
    public int recipeId;

    public Image(int id, String name, Date date, int recipeId)
    {
        this.id = id;
        this.name = name;
        this.date = date;
        this.recipeId = recipeId;
    }

    //********************************************************************************************************
    public int save() throws SQLException {
        boolean exists = this.id != 0 && DB.INSTANCE.executeSql(new DB.Handler<Boolean>() {
            @Override
            public Boolean  execute(Statement stmt) throws SQLException {
                ResultSet resultSet = stmt.getResultSet();
                return resultSet.next();
            }
        }, "SELECT * FROM Image WHERE id=?", this.id);
        // Если запись существовала, — обновляем её  (проверяется по id)
        // у вновь создаваемых записей id=0

        if  (exists)
        {
            DB.INSTANCE.executeSql("UPDATE Image SET name = ?, date_ = ?, recipe_id=?  WHERE id = ?",
                    this.name, this.date, this.recipeId, this.id);
            return this.id;
        }
        else
        {
            DB.INSTANCE.executeSql("INSERT INTO Image (id, name, date_, recipe_id) VALUES(?,?,?,?)",
                    this.id, this.name, this.date, this.recipeId);
            return this.id;
        }
    }
    //********************************************************************************************************
    public static Image getById(int id) {
        return DB.INSTANCE.executeSql(new DB.Handler<Image>() {
            @Override
            public Image execute(Statement stmt) throws SQLException {
                ResultSet resultSet = stmt.getResultSet();
                resultSet.next();
                return  new Image(
                        resultSet.getInt("id"),
                        resultSet.getString("name"),
                        resultSet.getDate("date_"),
                        resultSet.getInt("recipe_id"));
            }
        }, "SELECT * FROM Image WHERE id=?", id);
    }

    //********************************************************************************************************
    public static ArrayList<Image> getAll()
    {
        return DB.INSTANCE.executeSql(new DB.Handler<ArrayList<Image>>() {
            @Override
            public ArrayList<Image> execute(Statement stmt) throws SQLException {
                ArrayList<Image> result = new ArrayList<Image>();
                ResultSet resultSet = stmt.getResultSet();
                while (resultSet.next())
                {
                    result.add(new Image(
                            resultSet.getInt("id"),
                            resultSet.getString("name"),
                            resultSet.getDate("date_"),
                            resultSet.getInt("recipe_id")));
                }
                return result;

            }
        }, "SELECT * FROM Image");
    }
    //********************************************************************************************************
    public String toString()
    {
        return name;
    }
    //********************************************************************************************************
    public void delete(Context context) {
        this.deleteFile(context);
        DB.INSTANCE.executeSql("DELETE FROM Image WHERE id=?", this.id);
    }
    //********************************************************************************************************
    @Override
    public boolean equals(Object image)
    {
        try{
            return ( (this.id==((Image)image).id) &&
                    (this.name.equals(((Image)image).name))&&
                    (this.date==((Image)image).date) );
        }
        catch (ClassCastException e)
        {
            return false;
        }

    }
    //********************************************************************************************************
    public String getFilePath(Context context)
    {
        return FileUtils.getPath(context, FileUtils.FolderType.IMAGES).getPath()+"/"+ this.id + ".png";
    }
    //******************************************************************************************************************

    /**
     * Удаляет файл картинки
     * @param context
     */
    public void deleteFile(Context context)
    {
        FileUtils.deleteFile(this.getFilePath(context));
    }


    //******************************************************************************************************************
    public static ArrayList<Image> getByRecipe(int id) {
        return DB.INSTANCE.executeSql(new DB.Handler<ArrayList<Image>>() {
            @Override
            public ArrayList<Image> execute(Statement stmt) throws SQLException {
                ArrayList<Image> result = new ArrayList<Image>();
                ResultSet resultSet = stmt.getResultSet();
                while (resultSet.next())
                {
                    result.add(new Image(
                            resultSet.getInt("id"),
                            resultSet.getString("name"),
                            resultSet.getDate("date_"),
                            resultSet.getInt("recipe_id")));
                }
                return result;

            }
        }, "SELECT * FROM Image WHERE recipe_id=?",id);
    }
    //******************************************************************************************************************
}
